package com.http.nio.core;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;

/**
 * @author YL
 */
public class RequestWorker implements Runnable {

    private Request request;

    private SelectionKey key;

    private CloudService cloudService;

    public RequestWorker(Request request, SelectionKey key, CloudService cloudService) {
        this.request = request;
        this.key = key;
        this.cloudService = cloudService;
    }

    @Override
    public void run() {
        Response response = new Response();
        cloudService.doService(request, response);
        // 响应头部
        byte[] resHeader = HttpParser.encodeResHeader(response);
        // 响应体
        byte[] body = response.getOutPutStream().toByteArray();
        ByteBuffer byteBuffer = ByteBuffer.allocate(resHeader.length + body.length);
        byteBuffer.put(resHeader);
        byteBuffer.put(body);
        byteBuffer.flip();
        // 将输出流绑定至附件
        key.attach(byteBuffer);
        // 注册写事件
        key.interestOps(SelectionKey.OP_WRITE);
        key.selector().wakeup();
    }

}
